/**
 * 对于请求的一些简单封装 主要是为了统一处理
 * 
 * 
 */
;
(function(windom, $) {
	// 使用$.ajaxSetup 进行部分全局设置;
	$.ajaxSetup( {
	    headers: { // 默认添加请求头
	        "token": storage.get("token")
			}
	    });
	var request = {};
	request.complete = function(jqXHR, statu) {
		if ("success" == status) {
			// jqXHR.getResponseHeader("willExpire");
		}
	};
	var _default = {
		type: 'get',
		dataType: 'json',
		complete: request.complete,
		error: function(jqXHR, textStatus, errorMsg) { // 出错时默认的处理函数
			console.error('发送AJAX请求到"' + this.url + '"时出错[' + jqXHR.status + ']：' + errorMsg);
			$.alert("请求失败:" + jqXHR.status + ":" + errorMsg, "请求失败");
		}
	};
	/**
	 * ajax get 请求
	 * @param {Object} url
	 * @param {Object} fn success callback
	 * @param {Object} options
	 * @param {boolean} needLogin: 是否需要登陆, 默认需要
	 */
	request.get = function(url, options, fn, needLogin) {
		if (!common.isWholeUrl(url)) {
			url = base_url + url;
		}

		options = $.extend(true, {}, _default, options || {});
		needLogin = needLogin === false ? false : true;
		if (needLogin) {
			request.addToken(options);
		}
		$.ajax(url, options).done(function(result) {
			common.alert(result, function() {
				if ($.isFunction(fn)) {
					if ($.isFunction(fn)) {
						fn(result);
					}
				}else if(typeof(fn)=='string'){
					common.callFunction(fn, result);
				}
			},options.confirm);

		});
	};
	/**同步的get请求*/
	request.getSync = function(url, options, fn, needLogin) {
		options = options || {};
		options.async = false;
		request.get(url, options, fn, needLogin);
	}
	/**ajax post 请求
	 * @param {Object} url
	 * @param {Object} options  options about ajax
	 * @param {Object} fn fn success callback
	 * @param {boolean} needLogin: 是否需要登陆, 默认需要
	 */
	request.post = function(url, options, fn, needLogin) {
		options = options || {};
		options.type = 'post';
		request.get(url, options, fn, needLogin);
	}

	/**同步的post请求*/
	request.postSync = function(url, options, fn, needLogin) {
		options = options || {};
		options.async = false;
		request.post(url, options, fn, needLogin);
	}

	/**
	 * 请求新增headers的token信息 
	 */
	request.addToken = function(obj) {
		if (!obj) return;
		if (Object.prototype.toString.call(obj) === '[object Object]') {
			var headers = obj.headers;
			if (!headers) {
				headers = {};
				obj.headers = headers;
			}
			headers.token = storage.get("token");
		}
	}
	windom.$request = request;
})(window, jQuery);
